﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows.Controls;
using XWord.WPF.ApplicationFramework.Extensions;

namespace XWord.WPF.Behaviors
{
    public class MultiSelectOneBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.SelectionMode = SelectionMode.Multiple;
            AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
            base.OnAttached();
        }

        void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AssociatedObject.SelectedItem == null) return;


            if (e.AddedItems != null && e.AddedItems.Count == 1 && AssociatedObject.SelectedItems.Count > 1)
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                   {
                       ListBoxItem item = AssociatedObject.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]) as ListBoxItem;
                       var checkBox = item.FindVisualChild<CheckBox>();
                       if (!checkBox.IsMouseOver && AssociatedObject.IsMouseOver)
                       {
                           AssociatedObject.SelectedItem = e.AddedItems[0];
                       }
                   }), System.Windows.Threading.DispatcherPriority.Normal);
            }
        }
    }
}
